﻿//-------------------------------------------------------------------------------------------------------------------------------------
// Copyright (C) 2005 greatelsoft.com All Rights Reserved
//-------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Data.Common;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using GTS.Channel.Api.Entity;
using Pub.Class;

namespace GTS.Channel.Api.Helper {
    /// <summary>
    /// Job执行操作类
    /// 
    /// 修改纪录
    ///     2012-04-01 版本：1.0 系统自动创建此类
    /// 
    /// </summary>
    public partial class JobExecResultHelper {
        /// <summary>
        /// Job执行缓存多少秒 x 5
        /// </summary>
        public static int cacheSeconds = 1440;
        /// <summary>
        /// Job执行添加记录
        /// </summary>
        /// <param name="jobExecResult">Job执行实体类</param>
        /// <param name="delCache">添加成功后清理的CACHE key，支持正则</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时使用ConnString连接</param>
        /// <returns>返回添加成功后的ID</returns>
        public static Int64 Insert(JobExecResult jobExecResult, string dbkey = "", string[] delCache = null) {
            string strSql = new SQL().Insert(JobExecResult._)
                .Value(JobExecResult._JobID, jobExecResult.JobID)
                .Value(JobExecResult._StatusResult, jobExecResult.StatusResult)
                .Value(JobExecResult._CreateTime, jobExecResult.CreateTime)
                .ToString();
            strSql += ";select SCOPE_IDENTITY();";
            object objValue = dbkey.IsNullEmpty() ? Data.GetScalar(strSql) : Data.Pool(dbkey).GetScalar(strSql);
            if (objValue.IsAllNull()) return 0;
            Int64 value = objValue.ToBigInt();
            if (delCache.IsNull()) return value;
            foreach (string s in delCache) {
                if (s.IndexOf("(") == -1 || s.IndexOf("[") == -1)
                    Cache2.Remove(s.IndexOf("Cache_") == -1 ? "JobExecResultCache_" + s : s);
                else
                    Cache2.RemoveByPattern(s.IndexOf("Cache_") == -1 ? "(JobExecResultCache_" + s + ")" : s);
            }
            return value;
        }
        /// <summary>
        /// Job执行添加记录
        /// </summary>
        /// <param name="jobExecResult">Job执行实体类</param>
        /// <returns>返回添加成功后的ID</returns>
        public static Int64 Insert(JobExecResult jobExecResult, string dbkey = "") {
            return Insert(jobExecResult, dbkey, null);
        }
        /// <summary>
        /// Job执行修改记录
        /// </summary>
        /// <param name="jobExecResult">Job执行实体类</param>
        /// <param name="where">修改时附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="delCache">修改成功后清理的CACHE key，支持正则</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时使用ConnString连接</param>
        /// <returns>修改是否成功</returns>
        public static bool Update(JobExecResult jobExecResult, string dbkey = "", string where = "", string[] delCache = null) {
            if (jobExecResult.JobID.IsNull()) return false;
            string strSql = new SQL().Update(JobExecResult._)
                .Set(JobExecResult._StatusResult, jobExecResult.StatusResult)
                .Set(JobExecResult._CreateTime, jobExecResult.CreateTime)
                .Where("1=1").Where(new Where()
                    .And(JobExecResult._JobID, jobExecResult.JobID, Operator.Equal, true)
                ).ToString();
            if (!where.IsNullEmpty()) strSql += where;
            int value = dbkey.IsNullEmpty() ? Data.ExecSql(strSql) : Data.Pool(dbkey).ExecSql(strSql);
            if (value <= 0) return false;
            if (delCache.IsNull()) return true;
            foreach (string s in delCache) {
                if (s.IndexOf("(") == -1 || s.IndexOf("[") == -1)
                    Cache2.Remove(s.IndexOf("Cache_") == -1 ? "JobExecResultCache_" + s : s);
                else
                    Cache2.RemoveByPattern(s.IndexOf("Cache_") == -1 ? "(JobExecResultCache_" + s + ")" : s);
            }
            return true;
        }
        /// <summary>
        /// Job执行修改记录
        /// </summary>
        /// <param name="jobExecResult">Job执行实体类</param>
        /// <returns>修改是否成功</returns>
        public static bool Update(JobExecResult jobExecResult, string dbkey = "") {
            return Update(jobExecResult, dbkey, "", null);
        }
        /// <summary>
        /// Job执行修改多条记录
        /// </summary>
        /// <param name="jobIDList">Job执行编号列表，用“,”号分隔</param>
        /// <param name="jobExecResult">Job执行实体类</param>
        /// <param name="where">修改时附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="delCache">修改成功后清理的CACHE key，支持正则</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时使用ConnString连接</param>
        /// <returns>修改是否成功</returns>
        public static bool UpdateByIDList(string jobIDList,  JobExecResult jobExecResult, string dbkey = "", string where = "", string[] delCache = null) {
            string strSql = new SQL().Update(JobExecResult._)
                .Set(JobExecResult._StatusResult, jobExecResult.StatusResult)
                .Set(JobExecResult._CreateTime, jobExecResult.CreateTime)
                .Where("1=1").Where(new Where()
                    .And(JobExecResult._JobID, "(" + jobIDList + ")", Operator.In)
                ).ToString();
            if (!where.IsNullEmpty()) strSql += where;
            int value = dbkey.IsNullEmpty() ? Data.ExecSql(strSql) : Data.Pool(dbkey).ExecSql(strSql);
            if (value <= 0) return false;
            if (delCache.IsNull()) return true;
            foreach (string s in delCache) {
                if (s.IndexOf("(") == -1 || s.IndexOf("[") == -1)
                    Cache2.Remove(s.IndexOf("Cache_") == -1 ? "JobExecResultCache_" + s : s);
                else
                    Cache2.RemoveByPattern(s.IndexOf("Cache_") == -1 ? "(JobExecResultCache_" + s + ")" : s);
            }
            return true;
        }
        /// <summary>
        /// Job执行修改多条记录
        /// </summary>
        /// <param name="jobIDList">Job执行编号列表，用“,”号分隔</param>
        /// <param name="jobExecResult">Job执行实体类</param>
        /// <returns>修改是否成功</returns>
        public static bool UpdateByIDList(string jobIDList,  JobExecResult jobExecResult, string dbkey = "") {
            return UpdateByIDList(jobIDList,  jobExecResult, dbkey, "", null);
        }
         /// <summary>
        /// Job执行删除记录
        /// </summary>
        /// <param name="jobID">Job执行编号</param>
        /// <param name="where">修改时附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="delCache">删除成功后清理的CACHE key，支持正则</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时使用ConnString连接</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteByID(Int64? jobID,  string dbkey = "", string where = "", string[] delCache = null) {
            if (jobID.IsNull()) return false;
            string strSql = new SQL().Delete(JobExecResult._)
                .Where("1=1").Where(new Where()
                    .And(JobExecResult._JobID, jobID, Operator.Equal, true)
                ).ToString();
            if (!where.IsNullEmpty()) strSql += where;
            int value = dbkey.IsNullEmpty() ? Data.ExecSql(strSql) :  Data.Pool(dbkey).ExecSql(strSql);
            if (value != 1) return false;
            if (delCache.IsNull()) return true;
            foreach (string s in delCache) {
                if (s.IndexOf("(") == -1 || s.IndexOf("[") == -1)
                    Cache2.Remove(s.IndexOf("Cache_") == -1 ? "JobExecResultCache_" + s : s);
                else
                    Cache2.RemoveByPattern(s.IndexOf("Cache_") == -1 ? "(JobExecResultCache_" + s + ")" : s);
            }
            return true;
        }
        /// <summary>
        /// Job执行删除记录
        /// </summary>
        /// <param name="jobID">Job执行编号</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteByID(Int64? jobID, string dbkey = "") {
            return DeleteByID(jobID,  dbkey, "", null);
        }
        /// <summary>
        /// Job执行删除记录
        /// </summary>
        /// <param name="jobID">Job执行编号</param>
        /// <param name="where">修改时附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="delCache">删除成功后清理的CACHE key，支持正则</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时使用ConnString连接</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteByID(Int64 jobID,  string dbkey = "", string where = "", string[] delCache = null) {
            return DeleteByID((Int64?)jobID,  dbkey, where, delCache);
        }
        /// <summary>
        /// Job执行删除记录
        /// </summary>
        /// <param name="jobID">Job执行编号</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteByID(Int64 jobID, string dbkey = "") {
            return DeleteByID((Int64?)jobID,  dbkey, "", null);
        }
        /// <summary>
        /// Job执行删除多条记录
        /// </summary>
        /// <param name="jobIDList">Job执行编号列表，用“,”号分隔</param>
        /// <param name="where">删除时附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="delCache">修改成功后清理的CACHE key，支持正则</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时使用ConnString连接</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteByIDList(string jobIDList,  string dbkey = "", string where = "", string[] delCache = null) {
            string strSql = new SQL().Delete(JobExecResult._)
                .Where("1=1").Where(new Where()
                    .And(JobExecResult._JobID, "(" + jobIDList + ")", Operator.In)
                ).ToString();
            if (!where.IsNullEmpty()) strSql += where;
            int value = dbkey.IsNullEmpty() ? Data.ExecSql(strSql) :  Data.Pool(dbkey).ExecSql(strSql);
            if (value != 1) return false;
            if (delCache.IsNull()) return true;
            foreach (string s in delCache) {
                if (s.IndexOf("(") == -1 || s.IndexOf("[") == -1)
                    Cache2.Remove(s.IndexOf("Cache_") == -1 ? "JobExecResultCache_" + s : s);
                else
                    Cache2.RemoveByPattern(s.IndexOf("Cache_") == -1 ? "(JobExecResultCache_" + s + ")" : s);
            }
            return true;
        }
        /// <summary>
        /// Job执行删除多条记录
        /// </summary>
        /// <param name="jobIDList">Job执行编号列表，用“,”号分隔</param>
        /// <param name="where">删除时附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="delCache">修改成功后清理的CACHE key，支持正则</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时使用ConnString连接</param>
        /// <returns>删除是否成功</returns>
        public static bool DeleteByIDList(string jobIDList, string dbkey = "") {
            return DeleteByIDList(jobIDList,  dbkey, "", null);
        }
        /// <summary>
        /// Job执行按主键查询，返回数据的实体类
        /// </summary>
        /// <param name="jobID">Job执行编号</param>
        /// <param name="where">附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时随机取连接key</param>
        /// <returns>返回单条记录的实体类</returns>
        public static JobExecResult SelectByID(Int64 jobID,  string dbkey = "", string where = "") {
            string cacheNameKey = "JobExecResultCache_SelectByID_{0}".FormatWith(jobID + "_" +  "_" + where);
            return Cache2.Get<JobExecResult>(cacheNameKey, cacheSeconds, () => {
                string strSql = new SQL().From(JobExecResult._)
                    .Select(JobExecResult._JobID)
                    .Select(JobExecResult._StatusResult)
                    .Select(JobExecResult._CreateTime)
                    .Where("1=1").Where(new Where()
                        .And(JobExecResult._JobID, jobID, Operator.Equal)
                    ).ToString();
                if (!where.IsNullEmpty()) strSql += where;
                return Data.Pool(dbkey).GetDbDataReader(strSql).ToList<JobExecResult>().FirstOrDefault();
            });
        }
        /// <summary>
        /// Job执行按主键查询，返回数据的实体类
        /// </summary>
        /// <param name="jobID">Job执行编号</param>
        /// <returns>返回单条记录的实体类</returns>
        public static JobExecResult SelectByID(Int64 jobID, string dbkey = "") {
            return SelectByID(jobID,  dbkey, "");
        }
        /// <summary>
        /// 清除Job执行按主键查询的缓存
        /// </summary>
        public static void ClearCacheSelectByID(Int64 jobID,  string where = "") {
            string cacheName = "JobExecResultCache_SelectByID_{0}";
            string cacheNameKey = string.Format(cacheName, jobID + "_" +  "_" + where);
            Cache2.Remove(cacheNameKey);
        }
        /// <summary>
        /// Job执行查询数据，带分页
        /// </summary>
        /// <param name="pageIndex">当前第几页，从1开始</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="totalRecords">返回总记录数</param>
        /// <param name="where">附加条件，统一的前面要加链接符（and、or等等）</param>
        /// <param name="order">排序字段，不加“order by”</param>
        /// <param name="fieldList">设置需要返回的字段</param>
        /// <param name="dbkey">存在数据库连接池中的连接key，为空时随机取连接key</param>
        /// <param name="pageEnum">使用哪种分页方式（not_in、max_top、top_top、row_number、mysql、oracle、sqlite）</param>
        /// <returns>返回实体记录集</returns>
        public static IList<JobExecResult> SelectPageList(int pageIndex, int pageSize, out int totalRecords, string dbkey = "", string where = "", string order = "", string fieldList = "", PagerSQLEnum pageEnum = PagerSQLEnum.row_number) {
            totalRecords = 0;
            string cacheNameKey = "JobExecResultCache_SelectPageList_{0}_{1}_{2}_{3}_{4}".FormatWith(pageIndex, pageSize, where, order, fieldList);
            string cacheRecordsKey = "JobExecResultCache_RecordsSelectPageList_{0}_{1}_{2}_{3}_{4}".FormatWith(pageIndex, pageSize, where, order, fieldList);
            IList<JobExecResult> list = (IList<JobExecResult>)Cache2.Get(cacheNameKey);
            if (!list.IsNull()) { totalRecords = (int)Cache2.Get(cacheRecordsKey); return list; }

            using (PagerSQLHelper s = new PagerSQLHelper(pageEnum)) {
                PagerSql sql = s.GetSQL(pageIndex, pageSize, JobExecResult._, JobExecResult._JobID, fieldList.IfNullOrEmpty("[JobID],[StatusResult],[CreateTime],"), where, "", order);
                DataSet ds = Data.Pool(dbkey).GetDataSet(sql.DataSql + ";" + sql.CountSql);
                if (ds.IsNull()) return list;
                list = ds.Tables[0].ToList<JobExecResult>();
                totalRecords = ds.Tables[1].Rows[0][0].ToInt();
                ds.Dispose(); ds = null;
            }
            Cache2.Insert(cacheNameKey, list, cacheSeconds);
            Cache2.Insert(cacheRecordsKey, totalRecords, cacheSeconds);
            return list;
        }
        /// <summary>
        /// Job执行查询记录，带分页
        /// </summary>
        /// <param name="pageIndex">当前第几页，从1开始</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="totalRecords">返回总记录数</param>
        /// <returns>返回实体记录集</returns>
        public static IList<JobExecResult> SelectPageList(int pageIndex, int pageSize, out int totalRecords, string dbkey = "") {
            return SelectPageList(pageIndex, pageSize, out totalRecords, dbkey, "", "", "", PagerSQLEnum.row_number);
        }
        /// <summary>
        /// 清除Job执行查询记录，带分页的缓存
        /// </summary>
        public static void ClearCacheSelectPageList() {
            string cacheNameKey = "JobExecResultCache_SelectPageList_(.+?)";
            string cacheRecordsKey = "JobExecResultCache_RecordsSelectPageList_(.+?)";
            Cache2.RemoveByPattern(cacheNameKey);
            Cache2.RemoveByPattern(cacheRecordsKey);
        }
    }
}

